using System;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using umbraco.cms.businesslogic.member;
using umbraco.cms.businesslogic.property;
using System.Xml;
using System.Xml.Xsl;
using System.Collections;

namespace umbracoMemberControls.usercontrols
{
    public partial class showProfile : System.Web.UI.UserControl
    {

        #region Properties
        private string _layoutXslt = "umbShowProfile.xslt";
        private string _showOnProfile = "";
        private Member m = null;
        private TextBox tbName = new TextBox();
        private TextBox tbEmail = new TextBox();
        private TextBox tbPassword = new TextBox();
        private TextBox tbPasswordConfirm = new TextBox();
        private CompareValidator pwCompare = new CompareValidator();

        // Layout
        private string _beforeControls = "<fieldset id=\"umbracoEditProfileForm\">";
        private string _afterControls = "</fieldset>";
        private string _beforeLabel = "<p>";
        private string _afterLabel = "</p>";
        private string _beforeControl = "";
        private string _afterControl = "<br />";
        private string _labelName = "Name: ";
        private string _labelEmail = "Email: ";
        private string _labelPassword = "Password: ";
        private string _labelPasswordConfirm = "Confirm password: ";
        private string _errorMessagePassword = "Passwords doesn't match";

        private ArrayList _editControls = new ArrayList();

        public string ShowMemberFields
        {
            set { _showOnProfile = "," + value + ","; }
        }
        public string LayoutXslt
        {
            set { _layoutXslt = value; }
        }

        public string LabelName { set { _labelName = value; } }
        public string LabelEmail { set { _labelEmail = value; } }
        public string LabelPassword { set { _labelPassword = value; } }
        public string LabelPasswordConfirm { set { _labelPasswordConfirm = value; } }
        public string ErrorMessagePassword { set { _errorMessagePassword = value; } }
        #endregion

        private void Page_Load(object sender, System.EventArgs e)
        {
            PanelEdit.Visible = false;
            PanelProfile.Visible = false;

            string memberLogin = "";
            if (HttpContext.Current.Items["umbMemberLogin"] != null)
                memberLogin = HttpContext.Current.Items["umbMemberLogin"].ToString();
            else if (umbraco.helper.Request("member") != "")
                memberLogin = umbraco.helper.Request("member");

            // If no member parsed, then show current member...
            if (memberLogin == "" && umbraco.cms.businesslogic.member.Member.GetCurrentMember() != null)
                memberLogin = umbraco.cms.businesslogic.member.Member.GetCurrentMember().LoginName;

            if (memberLogin != "")
            {
                try
                {
                    m = Member.GetMemberFromLoginName(memberLogin);
                }
                catch { }

                if (m != null)
                {
                    if (umbraco.helper.Request("edit") == "true" && Member.GetCurrentMember().Id == m.Id)
                    {
                        PanelEdit.Visible = true;
                        editControls.Controls.Add(new LiteralControl(_beforeControls));

                        // add name, email and password
                        tbName.ID = "name";
                        tbName.Text = m.Text;
                        Label lbName = new Label();
                        lbName.ID = "lbName";
                        lbName.Text = _labelName;
                        lbName.CssClass = "umbAutoFormLabel";
                        lbName.AssociatedControlID = tbName.ID;
                        editControls.Controls.Add(new LiteralControl(_beforeLabel));
                        editControls.Controls.Add(lbName);
                        editControls.Controls.Add(new LiteralControl(_afterLabel));
                        editControls.Controls.Add(new LiteralControl(_beforeControl));
                        editControls.Controls.Add(tbName);
                        editControls.Controls.Add(new LiteralControl(_afterControl));

                        tbEmail.ID = "email";
                        tbEmail.Text = m.Email;
                        Label lbEmail = new Label();
                        lbEmail.ID = "lbEmail";
                        lbEmail.CssClass = "umbAutoFormLabel";
                        lbEmail.Text = _labelEmail;
                        lbEmail.AssociatedControlID = tbEmail.ID;
                        editControls.Controls.Add(new LiteralControl(_beforeLabel));
                        editControls.Controls.Add(lbEmail);
                        editControls.Controls.Add(new LiteralControl(_afterLabel));
                        editControls.Controls.Add(new LiteralControl(_beforeControl));
                        editControls.Controls.Add(tbEmail);
                        editControls.Controls.Add(new LiteralControl(_afterControl));

                        tbPassword.ID = "password";
                        tbPassword.TextMode = TextBoxMode.Password;
                        tbPasswordConfirm.ID = "passwordConfirm";
                        tbPasswordConfirm.TextMode = TextBoxMode.Password;
                        Label lbPassword = new Label();
                        lbPassword.CssClass = "umbAutoFormLabel";
                        lbPassword.ID = "lbPassword";
                        lbPassword.Text = _labelPassword;
                        lbPassword.AssociatedControlID = tbPassword.ID;                        
                        editControls.Controls.Add(new LiteralControl(_beforeLabel));
                        editControls.Controls.Add(lbPassword);
                        editControls.Controls.Add(new LiteralControl(_afterLabel));
                        editControls.Controls.Add(new LiteralControl(_beforeControl));
                        editControls.Controls.Add(tbPassword);

                        // Validation of passwords
                        pwCompare.ControlToValidate = tbPasswordConfirm.ID;
                        pwCompare.ControlToCompare = tbPassword.ID;
                        pwCompare.ErrorMessage = _errorMessagePassword + "<br/>";
                        pwCompare.Display = ValidatorDisplay.Dynamic;
                        Label lbPasswordConfirm = new Label();
                        lbPasswordConfirm.CssClass = "umbAutoFormLabel";
                        lbPasswordConfirm.ID = "lbPasswordConfirm";
                        lbPasswordConfirm.Text = _labelPasswordConfirm;
                        lbPasswordConfirm.AssociatedControlID = tbPasswordConfirm.ID;
                        editControls.Controls.Add(new LiteralControl(_afterControl));
                        editControls.Controls.Add(new LiteralControl(_beforeLabel));
                        editControls.Controls.Add(lbPasswordConfirm);
                        editControls.Controls.Add(new LiteralControl(_afterLabel));
                        editControls.Controls.Add(new LiteralControl(_beforeControl));
                        editControls.Controls.Add(pwCompare);
                        editControls.Controls.Add(tbPasswordConfirm);
                        editControls.Controls.Add(new LiteralControl(_afterControl));



                        umbraco.cms.businesslogic.member.MemberType mt = new umbraco.cms.businesslogic.member.MemberType(m.ContentType.Id);
                        foreach (Property p in m.getProperties)
                        {
                            if (mt.MemberCanEdit(p.PropertyType))
                            {
                                umbraco.interfaces.IDataType df = p.PropertyType.DataTypeDefinition.DataType;
                                df.DataEditor.Editor.ID = p.PropertyType.Alias;
                                ((Control)df.DataEditor.Editor).ID = p.PropertyType.Alias;
                                df.Data.PropertyId = p.Id;
                                if (!IsPostBack)
                                    df.Data.Value = p.Value;


                                Label lbField = new Label();
                                lbField.ID = "lbField" + p.PropertyType.Alias;
                                lbField.Text = p.PropertyType.Name;
                                lbField.CssClass = "umbAutoFormLabel";
                                lbField.AssociatedControlID = df.DataEditor.Editor.ID;

                                editControls.Controls.Add(new LiteralControl(_beforeLabel));
                                editControls.Controls.Add(lbField);
                                editControls.Controls.Add(new LiteralControl(_afterLabel));

                                editControls.Controls.Add(new LiteralControl(_beforeControl));
                                editControls.Controls.Add(df.DataEditor.Editor);
                                editControls.Controls.Add(new LiteralControl(_afterControl));
                                _editControls.Add(df);
                            }
                        }
                        editControls.Controls.Add(new LiteralControl(_afterControls));
                    }
                    else
                    {
                        XmlDocument xd = new XmlDocument();
                        XmlNode MemberXml = m.ToXml(xd, false);


                        // If no profile data has been written directly to the macro,
                        // then use the ones specified in the ui
                        // Maybe hide some entries
                        if (_showOnProfile != "")
                        {
                            foreach (XmlNode xn in MemberXml.SelectNodes("//data"))
                            {
                                if (("," + _showOnProfile + ",").IndexOf("," + xn.Attributes.GetNamedItem("alias").Value + ",") == -1)
                                    MemberXml.RemoveChild(xn);
                            }
                        }
                        else
                        {
                            foreach (Property p in m.getProperties)
                            {
                                MemberType mt = new MemberType(m.ContentType.Id);
                                if (!mt.ViewOnProfile(p.PropertyType))
                                {
                                    XmlNode xn = MemberXml.SelectSingleNode("//data [@alias = '" + p.PropertyType.Alias + "']");
                                    if (xn != null)
                                        MemberXml.RemoveChild(xn);
                                }
                            }
                        }

                        xd.AppendChild(MemberXml);
                        Xml1.TransformSource = "/xslt/" + _layoutXslt;
                        XsltArgumentList xsltArgs = umbraco.macro.AddXsltExtensions();
                        umbraco.library lib = new umbraco.library();
                        xsltArgs.AddExtensionObject("urn:umbraco.library", lib);
                        Xml1.TransformArgumentList = xsltArgs;
                        Xml1.XPathNavigator = xd.CreateNavigator();
                        PanelProfile.Visible = true;
                    }
                }
                else
                    Trace.Warn("showProfile", "No member exists with login '" + HttpContext.Current.Items["umbMemberLogin"].ToString() + "'");
            }
            else
            {
                Trace.Warn("showProfile", "No member found in item 'umbMemberLogin'");
            }
        }

        #region Web Form Designer generated code
        override protected void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);
        }

        /// <summary>
        ///		Required method for Designer support - do not modify
        ///		the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.UpdateMember.Click += new System.EventHandler(this.UpdateMember_Click);
        }
        #endregion

        private void UpdateMember_Click(object sender, System.EventArgs e)
        {
            if (Page.IsValid)
            {
                foreach (object o in _editControls)
                {
                    umbraco.interfaces.IDataType ctr = ((umbraco.interfaces.IDataType)o);
                    ctr.Data.PropertyId = m.getProperty(ctr.DataEditor.Editor.ID).Id;
                    ctr.DataEditor.Save();
                }

                // Name, email 
                m.Text = tbName.Text;
                m.Email = tbEmail.Text;

                // Password
                if (tbPassword.Text != "" && tbPassword.Text == tbPasswordConfirm.Text)
                    m.Password = tbPassword.Text;

                m.XmlRemoveFromDB();
                Response.Redirect(Request.RawUrl.ToLower().Replace("edit=true", ""), true);
            }
        }
    }
}
